package com.jt.aop;

import com.jt.util.ObjectMapperUtil;
import org.apache.ibatis.binding.MapperMethod;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.ShardedJedis;

import java.util.Arrays;

@Aspect//这是一个AOP类
@Component//将这个类交给spring管理
public class CacheAOP {
   /* @Autowired(required = false)
    private ShardedJedis jedis;*/

    @Autowired(required = false)
    private JedisSentinelPool jedisSentinelPool;
    @Autowired
    private JedisCluster jedis;

    @Around("@annotation(cacheFind)")//只有around才能对方法进行操作，@Before,@After只能看着

    public Object around(ProceedingJoinPoint joinPoint,CacheFind cacheFind){
//        Jedis jedis=jedisSentinelPool.getResource();

        Object result= null;
        String key=cacheFind.key();
        String argString= Arrays.toString(joinPoint.getArgs());
        key=key+"::"+argString;
        System.out.println(key);//拿出并且初始化key值，为后面判断key是否存在作准备
        try {
            if (jedis.exists(key)){
                String json=jedis.get(key);
                MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();//这个要导入反射包，导入其它包会运行报错，并在下面抛出异常
                Class returnType = methodSignature.getReturnType();//获得一个返回值得类类型
                result=ObjectMapperUtil.toObj(json, returnType);//将json串转换为Java对象
                System.out.println("看看缓存");
            }
            else {
                result=joinPoint.proceed();//如果没有，就继续运行原方法，并将返回值转换为字符串（json格式）存入缓存中
                String json=ObjectMapperUtil.toJSON(result);
                if (cacheFind.seconds()>0){
                    jedis.setex(key, cacheFind.seconds(), json);
                }else {
                    jedis.set(key, json);
                }
                System.out.println("没有，加一个");

            }
        }catch (Throwable throwable){
            throwable.printStackTrace();
            throw new RuntimeException();
        }
//        jedis.close();
        return result;
    }

}
